package model

import (
	"gorm.io/gorm"
	"smart-health-platforms/config"
	"time"
)

// 分销用户表
type DistributionUser struct {
	Id          uint32         `gorm:"column:id;type:int UNSIGNED;comment:分销用户主键id;primaryKey;not null;" json:"id"`                                // 分销用户主键id
	UserId      uint32         `gorm:"column:user_id;type:int UNSIGNED;comment:用户id;not null;" json:"user_id"`                                     // 用户id
	NickName    string         `gorm:"column:nick_name;type:varchar(50);comment:用户昵称;not null;" json:"nick_name"`                                  // 用户昵称
	TotalIncome float64        `gorm:"column:total_income;type:decimal(10, 1);comment:总佣金;not null;default:0.0;" json:"total_income"`              // 总佣金
	Available   float64        `gorm:"column:available;type:decimal(10, 1);comment:可用金额;not null;default:0.0;" json:"available"`                   // 可用金额
	Frozen      float64        `gorm:"column:frozen;type:decimal(10, 1);comment:冻结金额;not null;default:0.0;" json:"frozen"`                         // 冻结金额
	ParentId    uint32         `gorm:"column:parent_id;type:int UNSIGNED;comment:父级id;not null;default:0;" json:"parent_id"`                       // 父级id
	CreatedAt   time.Time      `gorm:"column:created_at;type:datetime(3);comment:参与分销时间;not null;default:CURRENT_TIMESTAMP(3);" json:"created_at"` // 参与分销时间
	UpdatedAt   time.Time      `gorm:"column:updated_at;type:datetime(3);default:NULL;" json:"updated_at"`
	DeletedAt   gorm.DeletedAt `gorm:"column:deleted_at;type:datetime(3);default:NULL;" json:"deleted_at"`
}

// 设置与数据库表的映射关系
func (du *DistributionUser) TableName() string {
	return "distribution_user"
}

// 设置分销用户
func (du *DistributionUser) Create() error {
	return config.DB.Create(&du).Error
}

// 修改分销用户
func (du *DistributionUser) Update(parentId int64) error {
	return config.DB.Model(&du).Where("user_id = ?", du.UserId).Update("parent_id", parentId).Error
}

// 删除分销用户
func (du *DistributionUser) Remove() error {
	return config.DB.Where("user_id = ?", du.UserId).Delete(&du).Error
}

// 获取一级分销用户
func (du *DistributionUser) GetUserId(userId int64) error {
	return config.DB.Where("user_id = ?", userId).Limit(1).Find(&du).Error
}

// 获取二级分销用户
func (du *DistributionUser) GetSecondLevelUser(userId int64) error {
	return config.DB.Where("parent_id = ?", userId).Limit(1).Find(&du).Error
}

// 查询分销用户下两级用户
func (du *DistributionUser) GetTwoLevelUser() (disUserList []*DistributionUser, err error) {
	//先查询当前用户的一级分销用户
	var firstLevel []*DistributionUser
	err = config.DB.Model(&DistributionUser{}).
		Select("distribution_user.*,users.nick_name").
		Joins("join users on distribution_user.user_id = users.id").
		Where("parent_id = ?", du.UserId).
		Find(&firstLevel).Error
	if err != nil {
		return
	}
	//若没有一级用户，则直接返回为空
	if len(firstLevel) == 0 {
		return
	}
	//收集一级分销用户的id，用于查询二级分销用户
	firstIds := make([]int64, len(firstLevel))
	for i, user := range firstLevel {
		firstIds[i] = int64(user.UserId)
	}
	//查询二级分销用户
	var secondLevel []*DistributionUser
	err = config.DB.Model(&DistributionUser{}).
		Select("distribution_user.*,users.nick_name").
		Joins("join users on distribution_user.user_id = users.id").
		Where("parent_id IN (?)", firstIds).
		Find(&secondLevel).Error
	if err != nil {
		return
	}

	//合并一级和二级分销用户
	disUserList = append(firstLevel, secondLevel...)
	return disUserList, nil
}

// 获取用户信息
func (du *DistributionUser) GetUserInfo() error {
	return config.DB.Where("user_id = ?", du.UserId).Limit(1).Find(&du).Error
}

// 根据用户id查询用户信息
func (du *DistributionUser) GetUserByInfo(tx *gorm.DB, userId int64) error {
	return config.DB.Where("user_id = ?", du.UserId).Limit(1).Find(&du).Error
}

// 修改总佣金
func (du *DistributionUser) UpdateTotalIncome(tx *gorm.DB) error {
	return config.DB.Model(&du).Where("user_id = ?", du.UserId).Update("total_income", gorm.Expr("total_income + ?", du.TotalIncome)).Error
}

// 减少总佣金
func (du *DistributionUser) ReduceTotalIncome(tx *gorm.DB) error {
	return config.DB.Model(&du).Where("user_id = ?", du.UserId).Update("total_income", gorm.Expr("total_income - ?", du.TotalIncome)).Error
}

// 修改可用金额
func (du *DistributionUser) UpdateAvailable(tx *gorm.DB) error {
	return config.DB.Model(&du).Where("user_id = ?", du.UserId).Update("available", gorm.Expr("available + ?", du.Available)).Error
}

// 减少可用金额
func (du *DistributionUser) ReduceAvailable(tx *gorm.DB) error {
	return config.DB.Model(&du).Where("user_id = ?", du.UserId).Update("available", gorm.Expr("available - ?", du.Available)).Error
}

// 修改冻结金额
func (du *DistributionUser) UpdateFrozen(tx *gorm.DB) error {
	return config.DB.Model(&du).Where("user_id = ?", du.UserId).Update("frozen", gorm.Expr("frozen + ?", du.Frozen)).Error
}

// 减少冻结金额
func (du *DistributionUser) ReduceFrozen(tx *gorm.DB) error {
	return config.DB.Model(&du).Where("user_id = ?", du.UserId).Update("frozen", gorm.Expr("frozen - ?", du.Frozen)).Error
}

// 设置排行榜
func (du *DistributionUser) SetRank() (disUserList []*DistributionUser, err error) {
	err = config.DB.Model(&DistributionUser{}).
		Select("distribution_user.*,users.nick_name").
		Joins("join users on distribution_user.user_id = users.id").
		Order("total_income desc").
		Limit(10).
		Find(&disUserList).Error
	return
}
